import React, { memo, useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Switch, Radio, Drawer, Button, Modal, Form, Input, Select, Upload, Table, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { service_package, team_addPackage, team_doctor, team_editteam, team_exit, team_Package, team_search_a, team_search_b, team_Setsstatus_a, team_yichuPackage } from '../../../axios/api1';
import '../style/pub.scss'
import '../style/joindetail.scss'
import '../style/addTeam.scss'
import '../style/package.scss'
import "../style/doctordetail.scss"
function JoinDetail(props: any) {
    // 定义类型
    interface Detail {
        key: React.Key,
        name: String,
        images: String,
        captain: String,
        orgin: String,
        title: String,
        time: string,
        status: boolean,
        score: String,
        person: String
    }
    // 定义团队医生详情的类型
    interface DoctorDetail {
        key: React.Key,
        name: String,
        images: String,
        phone: String,
        sex: String
        person: String,
        score: String,
        doctorbreif: String,
        doctoradept: String,
        status: boolean
    }
    // 定义服务包的类型
    interface PackageDetail {
        packagename: String,
        images: String,
        packageobject: String,
        title: {},
        serviceAvailable: []
        packageStatus: Number,
        period: String,
        introduce: String
    }
    // 定义服务包项目类型
    interface DataType {
        Availableid: React.Key,
        Availablename: string,
        Availablenum: string,
        Availabletype: string,
        Availableintroduce: string,
    }
    // 定义跳路由
    const push = useNavigate()
    // 定义接收路由参数
    const [params, setParams] = useSearchParams()
    var key = params.get('key')
    // 表单
    const [form] = Form.useForm()
    // 定义状态用来获取列表
    const [joindetail, setJoinDetail] = useState<Detail>()
    // 定义一个状态用来存储团队标签
    const [title, setTitle] = useState<any[]>([])
    // 控制加入确认的弹出框的显示隐藏
    const [confirm, setConfirm] = useState(false)
    // 控制编辑团队信息的弹出框的显示隐藏
    const [edit, setEdit] = useState(false)
    // 定义一个状态用来存放加入该团队的医生
    const [doctor, setDoctor] = useState([])
    // 定义一个状态，用来存放该团队的服务包的信息
    const [packageDetail, setPackageDetail] = useState([])
    // 设置状态，用来控制抽屉的显示或隐藏
    const [open, setOpen] = useState(false);
    // 设置状态，用来控制服务包详情的显示隐藏
    const [openPackage, setOpenPackage] = useState(false)
    // 定义一个状态，用来存放每个医生的具体详情
    const [doctorDetail, setDoctorDetail] = useState<DoctorDetail>()
    // 定义一个状态，用来存放每个服务包的具体详情
    const [packageXinxi, setpackcgeXinxi] = useState<any>([])
    const [bao, setBao] = useState(false)
    // 定义一个状态，用来存放点击的key值，使用key值用来发请求
    const [teamkey, setTeamKey] = useState()
    // 定义上传的头像
    const [imageUrl, setImageUrl] = useState<string>();
    // 定义状态用来存储服务包列表
    const [servicePackage, setServicePackage] = useState([])
    const teamSearch = () => {
        team_search_b({ key: key }).then((res) => {
            // console.log(res)
            if (res.data.code == 200) {
                // 获取点击的团队的详情信息
                setJoinDetail(res.data.teamlist)
                console.log(res.data.teamlist)
                // 获取标签
                var til = Object.values(res.data.teamlist.title)
                setTitle(til)
                // 获取团队医生列表
                setDoctor(res.data.teamlist.teamMember)
                // 获取团队服务包列表
                setPackageDetail(res.data.teamlist.servicePackage)
                console.log(doctor);
                console.log(res.data.teamlist.servicePackage);
            }
        })
        service_package().then((res) => {
            console.log(res.data.servicepackage)
            setServicePackage(res.data.servicepackage)
        })
    }
    useEffect(() => {
        teamSearch()
    }, [key])
    console.log(packageDetail);

    const changeStatus = (val: any) => {
        console.log(val);
        team_Setsstatus_a({ key: val }).then((res: any) => {
            console.log(res.data.status);

            if (res.data.status) {
                console.log(res.data.teamlist);
                setJoinDetail(res.data.teamlist)
                message.open({
                    type: 'success',
                    content: '已启用'
                })
            } else {
                console.log(res.data.teamlist);
                setJoinDetail(res.data.teamlist)
                message.open({
                    type: 'success',
                    content: '已禁用'
                })
            }

        })
    }
    // 显示医师详情抽屉
    const showDrawer = (id: string) => {
        console.log(id);
        // 将团队的id和医生的id一起传过去
        team_doctor({ teamid: joindetail?.key, doctorid: id }).then((res => {
            if (res.data.code == 200) {
                console.log(res.data.doctorDetail)
                setDoctorDetail(res.data.doctorDetail)
                setOpen(true);
            }
        }))
    };
    // 隐藏医师详情抽屉
    const onClose = () => {
        setOpen(false);
    };
    // 显示服务包详情抽屉
    const showPackage = (id: any) => {
        console.log(id);
        team_Package({ teamid: joindetail?.key, packageid: id }).then((res) => {
            console.log(res.data.packageDetail)
            if (res.data.code == 200) {
                var arr = []
                arr.push(res.data.packageDetail)
                setpackcgeXinxi(arr)
            }
        })
        setOpenPackage(true)
    }
    // 隐藏服务包详情抽屉
    const canclePackage = () => {
        setOpenPackage(false)
    }
    // 定义表格的每一列数据
    const columns: ColumnsType<DataType> = [
        {
            title: '项目编号',
            dataIndex: 'Availableid',
        },
        {
            title: '项目名称',
            dataIndex: 'Availablename',
        },
        {
            title: '次数',
            dataIndex: 'Availablenum',
            align: 'center'
        },
        {
            title: '项目类型',
            dataIndex: 'Availabletype',
            align: 'center'
        },
        {
            title: '项目介绍',
            dataIndex: 'Availableintroduce',
            align: 'center'
        }
    ];
    // 定义返回事件
    const back = () => {
        push(-1)
    }
    // 定义解散团队
    const exit = (key: any) => {
        setTeamKey(key)
        setConfirm(true)
    }
    // 确认解散当前队伍的事件
    const handleOk_a = () => {
        team_exit({ key: teamkey }).then((res) => {
            if (res.data.code == 200) {
                setConfirm(false);
                push("/MyLayout/Team/Manage")
                message.open({
                    type: 'success',
                    content: '已解散'
                })
            }
        })
    };
    // 确认解散当前队伍的cancel事件
    const handleCancel_a = () => {
        setConfirm(false);
    };
    // 编辑团队信息的显示隐藏
    const editok = () => {
        setEdit(false)
    }
    const editCancel = () => {
        setEdit(false)
    }
    // 编辑当前团队的信息
    const editTeam = (key: any) => {
        console.log(key);
        team_search_a({ captain: key }).then((res) => {
            console.log(res.data.teamlist)
            form.setFieldsValue(res.data.teamlist[0])
            // form.setFieldsValue({ origin: res.data.teamlist[0].origin })
        })
        console.log(key);
        setEdit(true)
    }
    // 上传头像
    const handleChange = (value: any) => {
        console.log(value);
    }
    // 编辑好团队信息后点击确认
    const finish = (value: any) => {
        console.log(value);
        team_editteam(value).then((res) => {
            if (res.data.code == 200) {
                setEdit(false)
                teamSearch()
                message.open({
                    type: 'success',
                    content: '编辑成功'
                })
            } else {
                message.open({
                    type: 'error',
                    content: res.data.msg
                })
            }
        })
    }
    // 移除服务包
    const Yichu = (val: any) => {
        console.log(val);
        team_yichuPackage({ key: joindetail?.key, packageid: val }).then((res) => {
            setPackageDetail(res.data.packageDetail)
            setOpenPackage(false)
            message.open({
                type: 'success',
                content: '已移除'
            })
            console.log(res.data);
        })

    }
    const options = [
        { value: '陕西省西安市雁塔区卫生服务站', label: '陕西省西安市雁塔区卫生服务站' },
        { value: '陕西省西安市长安区卫生服务站', label: '陕西省西安市长安区卫生服务站' },
        { value: '陕西省西安市未央区卫生服务站', label: '陕西省西安市未央区卫生服务站' },
        { value: '陕西省西安市新城区卫生服务站', label: '陕西省西安市新城区卫生服务站' },
        { value: '陕西省西安市灞桥区卫生服务站', label: '陕西省西安市灞桥区卫生服务站' }
    ]
    // 定义上传按钮
    const uploadButton = (
        <div>
            <div style={{ marginTop: 8 }}>点击上传</div>
        </div>
    );
    // 定义服务项目
    // 添加服务包
    const addpage = () => {
        setBao(true)
    }
    const handleCancel = () => {
        setBao(false)
    }
    const editdoctor = (val: any) => {
        push({ pathname: '/MyLayout/EditDoctor', search: `?data=${val}` })
    }
    // 选择服务包并插入进服务包列表中
    const packDetail = (id: any) => {
        console.log(id);
        team_addPackage({ key: joindetail?.key, packageid: id }).then((res) => {
            // console.log(res.data)
            if (res.data.code == 200) {
                teamSearch()
                setBao(false)

            }
        })
    }
    const back_a = () => {
        setOpen(false);
    }
    return (
        <div>
            {/* 标题部分 */}
            <h1 className='Headline'><span></span>我管理的团队详情</h1>
            <div className="header">
                <p className='h1'>
                    团队信息
                </p>
                <div className="team">
                    <p>团队编号：<span>{joindetail?.key}</span></p>
                    <p>团队名称：<span>{joindetail?.name}</span></p>
                    <p>团队标签：{
                        title.map((item, index) => {
                            return (
                                <span key={index}>{item}</span>
                            )
                        })
                    }</p>
                    <p>机构地址：<span>{joindetail?.orgin}</span></p>
                </div>
                <div className="xinxi">
                    <p>创建时间：<span>{joindetail?.time}</span></p>
                    <p>创建人：<span>{joindetail?.captain}</span></p>
                    <p>团队状态：<Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked checked={joindetail?.status} onChange={() => changeStatus(joindetail?.key)} /></p>
                </div>

                <p className='h1'>团队成员（{doctor?.length}）</p>
                {/* 医师详情的区域 */}
                <div className="member">
                    {
                        doctor?.map((item: any, index) => {
                            return (
                                <>
                                    {/* // 团队医生的区域 */}
                                    <div className='doctor' key={index} style={{ marginTop: 20, paddingBottom: 0 }}>
                                        <div className="top">
                                            <div className="right">
                                                <img src={item.images} alt="" />
                                            </div>
                                            <div className="left">
                                                <p>{item.name}<span>{item.role}</span></p>
                                                <p>签约人数：{item.person}</p>
                                                <p>医生评分：{item.score}</p>
                                            </div>
                                        </div>
                                        <div className="bottom">
                                            <Radio.Button value="default" onClick={() => showDrawer(item.key)}>医师详情</Radio.Button>
                                        </div>
                                    </div>
                                </>
                            )
                        })

                    }
                </div>
                <p className='h1'>服务包（{packageDetail.length}）</p>
                {/* 服务包详情 */}
                <div className="chuji">
                    {
                        packageDetail.map((item: any, index) => {
                            return (
                                <>
                                    {/* 服务包的区域 */}
                                    <div className="primary">
                                        {/* 通过数组的map进行响应式的渲染页面 */}
                                        <div className="basics">
                                            <img src={item.images} alt="" style={{ width: 136, height: 98 }} />
                                            <div className="right">
                                                <p>{item.packagename}</p>
                                                <p>服务对象：{item.packageobject}</p>
                                                <span>随访服务</span>
                                                <span>常规护理</span>
                                            </div>
                                            <div id="u6738-1" className="ax_default u6738" data-label="标签" style={{ visibility: 'inherit' }}>
                                                {/* <!-- Unnamed (矩形) --> */}
                                                <div id="u6738-1_state0" className="panel_state u6738_state0" data-label="State1" style={{ width: 80, height: 80, visibility: "inherit", position: 'absolute', top: 0, right: 0, overflow: 'clip' }}>
                                                    <p className={` ${item.packagestatus == 1 ? 'tab1' : 'tab'}`}>使用中</p>
                                                    <p className={` ${item.packagestatus == 2 ? 'tab2' : 'tab'}`}>待审核</p>
                                                    <p className={` ${item.packagestatus == 3 ? 'tab3' : 'tab'}`}>已停用</p>
                                                    <p className={` ${item.packagestatus == 4 ? 'tab4' : 'tab'}`}>已驳回</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div className="bottom">
                                            <Radio.Button value="default" onClick={() => showPackage(item.packageid)}>服务包详情</Radio.Button>
                                        </div>
                                    </div>
                                </>
                            )
                        })

                    }
                    <div className="page">
                        <div id="u5589" className="mouseOver" style={{ cursor: "pointer" }} onClick={addpage}>
                            <div className="text ">
                                <p style={{ fontSize: 16 }} id="cache2"><span style={{ fontSize: 36 }} id="cache3">+ </span></p>
                                <p style={{ fontSize: 16 }} id="cache3"><span id="cache3">添加服务包</span></p>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
            <div className="font">
                <Button type="primary" onClick={() => editTeam(joindetail?.key)}>
                    编辑团队信息
                </Button>
                <Button type="primary" danger onClick={() => exit(joindetail?.key)}>
                    解散团队
                </Button>
                <Button onClick={back}>
                    返回
                </Button>
            </div>
            <Modal title="解散确认？" open={confirm} style={{ width: 200 }} onOk={handleOk_a} onCancel={handleCancel_a}>
                <span>确认解散当前队伍吗？</span>
            </Modal>
            {/* 编辑团队信息 */}
            <Modal className='ant_body' title="编辑团队信息" open={edit} onOk={editok} onCancel={editCancel}>
                <Form
                    form={form}
                    onFinish={finish}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 14 }}
                    layout="horizontal"
                    style={{ width: 600 }}
                >
                    <Form.Item name='key' label="团队编号 ">
                        <Input disabled />
                    </Form.Item>
                    <Form.Item name='name' label="团队名称 ">
                        <Input />
                    </Form.Item>
                    <Form.Item label="团队头像">
                        <Upload action="upload.do" maxCount={1} listType="picture-card" onChange={(value: any) => handleChange(value)}>
                            <div>
                                <PlusOutlined />
                                <div style={{ marginTop: 8 }}>点击上传</div>
                            </div>
                        </Upload>
                    </Form.Item>
                    <Form.Item name="orgin" label="所属机构">
                        <Select placeholder="请选择" options={options} />
                    </Form.Item>
                    <Form.Item name="captain" label="团队队长">
                        <Input />
                    </Form.Item>
                    <Form.Item style={{ marginLeft: 200 }} >
                        <Button onClick={editCancel}>取消</Button>
                        <Button type='primary' htmlType='submit'>确认</Button>
                    </Form.Item>
                </Form>
            </Modal>
            {/* 医师详情（抽屉） */}
            <Drawer title="医生信息" placement="right" onClose={onClose} open={open} width={720}>
                <div >
                    <div className="doctorXinxi">
                        <div className='one'>
                            <p>医生编号：<span>{doctorDetail?.key}</span></p>
                            <p>医生姓名：<span>{doctorDetail?.name}</span></p>
                            <p>联系电话: <span>{doctorDetail?.phone}</span></p>
                        </div>
                        <div className="two">
                            <p>性别: <span>{doctorDetail?.sex}</span> </p>
                            <p className='jianjie'><p>医生简介：</p> <span>{doctorDetail?.doctorbreif}</span> </p>
                            <p className='shanchang'><p>医生擅长：</p><span>{doctorDetail?.doctoradept}</span> </p>
                        </div>

                    </div>
                    <div className="join">
                        <p>签约人数:<span className='jiange'>{doctorDetail?.person}</span> </p>
                        <p>医生评分:<span className='jiange'>{doctorDetail?.score}</span></p>
                        <p style={{ display: doctorDetail?.status ? 'block' : 'none' }} >账号状态：<span style={{ color: 'lightgreen', }}>启用中</span></p>
                        <p style={{ display: doctorDetail?.status ? 'none' : 'block' }} >账号状态：<span style={{ color: 'hotpink', }}>未启用</span></p>
                    </div>
                    <div className="font">
                        <Button type='primary' onClick={() => { editdoctor(doctorDetail?.key) }}>编辑医生信息</Button>
                        <Button onClick={back_a}>返回</Button>
                    </div>
                </div>
            </Drawer>
            {/* 服务包详情 */}
            <Drawer title="服务包信息" placement="right" onClose={canclePackage} open={openPackage} width={755}>

                {
                    packageXinxi.map((item: any, index: any) => {
                        console.log(item.servicesAvailable);
                        return (
                            <>
                                <div className="pack" key={index}>
                                    <img src={item?.images} alt="" style={{ width: 136, height: 72 }} />
                                    <p>{item?.packagename}</p>
                                    <p>服务对象：{item?.packageobject}</p>
                                    <p>签约周期：{item?.period}年（可续约）</p>
                                    <p>服务介绍{item?.introduce}</p>
                                </div>
                                <Table className='packDetails' columns={columns} style={{ fontSize: '12px' }} dataSource={item.servicesAvailable} />
                                <Button danger onClick={() => Yichu(item.packageid)}>移除服务包</Button>
                            </>

                        )
                    })
                }
            </Drawer>
            {/* 添加服务包、弹出详情 */}
            <Modal title="选择服务包" cancelText="取消" okText="确定" open={bao} onOk={addpage} onCancel={handleCancel}>
                {
                    // {/* 通过数组的map进行响应式的渲染页面 */}
                    servicePackage?.map((item: any) => {
                        return (
                            <div className="primary" key={item.packageid} onClick={() => packDetail(item.packageid)}>
                                <div className="basics">
                                    <img src={item.images} alt="" style={{ width: 136, height: 106 }} />
                                    <div className="right">
                                        <p>{item.packagename}</p>
                                        <p>服务对象：{item.packageobject}</p>
                                        <span>随访服务</span>
                                        <span>常规护理</span>
                                    </div>
                                    <div id="u6738-1" className='ax_default u6738' data-label="标签" style={{ visibility: 'inherit' }}>
                                        {/* <!-- Unnamed (矩形) --> */}
                                        <div id="u6738-1_state0" className="panel_state u6738_state0" data-label="State1" style={{ width: 80, height: 80, visibility: "inherit", position: 'absolute', top: 0, right: 0, overflow: 'clip' }}>
                                            <p className={` ${item.packagestatus == 1 ? 'tab1' : 'tab'}`}>使用中</p>
                                            <p className={` ${item.packagestatus == 2 ? 'tab2' : 'tab'}`}>待审核</p>
                                            <p className={` ${item.packagestatus == 3 ? 'tab3' : 'tab'}`}>已停用</p>
                                            <p className={` ${item.packagestatus == 4 ? 'tab4' : 'tab'}`}>已驳回</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )
                    })
                }
            </Modal>
        </div>
    );
}

export default memo(JoinDetail);